#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    boy = new QPerson("John");
    boy->setProperty("score",95);
    boy->setProperty("age",10);
    boy->setProperty("sex","Boy");
    connect(boy,&QPerson::ageChanged,this,&MainWindow::on_ageChanged);

    girl=new QPerson("Lily");
    girl->setProperty("score",81);
    girl->setProperty("age",20);
    girl->setProperty("sex","Girl");
    connect(girl,&QPerson::ageChanged,this,&MainWindow::on_ageChanged);
    ui->spinBoy->setProperty("isBoy",true);
    ui->spinGirl->setProperty("isBoy",false);

    connect(ui->spinGirl,SIGNAL(valueChanged(int)),this,SLOT(on1_spin_valueChanged(int)));
    connect(ui->spinBoy,SIGNAL(valueChanged(int)),this,SLOT(on1_spin_valueChanged(int)));

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_ageChanged(int value){
    Q_UNUSED(value);
    QPerson *aPerson=qobject_cast<QPerson  *>(sender());
    QString hisName = aPerson->property("name").toString();
    QString hisSex = aPerson->property("sex").toString();
    int hisAge = aPerson->age();
    ui->txtEdit->append(hisName+","+hisSex+QString::asprintf(",age=%d",hisAge));
}
void MainWindow::on1_spin_valueChanged(int value){
    Q_UNUSED(value);
    QSpinBox *spinBox=qobject_cast<QSpinBox* >(sender());
    if (spinBox->property("isBoy").toBool())
        boy->setAge(spinBox->value());
    else {
        girl->setAge(spinBox->value());
    }
}
void MainWindow::on_btnClassInfo_clicked(){
    const QMetaObject *meta = boy->metaObject();
    ui->txtEdit->clear();
    ui->txtEdit->append("==raw object info==\n");
    ui->txtEdit->append(QString("class name: %1 \n").arg(meta->className() ));
    ui->txtEdit->append("perperty");
    for(int i=meta->propertyOffset();i<meta->propertyCount();i++){
        QMetaProperty prop = meta->property(i);
        const char* propName=prop.name();
        QString propValue = boy->property(propName).toString();
        ui->txtEdit->append(QString("property=%1,value=%2").arg(propName).arg(propValue));
    }
    ui->txtEdit->append("");
    ui->txtEdit->append("classInfo");
    for(int i=meta->classInfoOffset();i<meta->classInfoCount();++i){
        QMetaClassInfo classInfo=meta->classInfo(i);
        ui->txtEdit->append(QString("Name=%1;Value=%2").arg(classInfo.name()).arg(classInfo.value()));
    }
}
void MainWindow::on_btnBoyInc_clicked(){
    boy->incAge();
};
void MainWindow::on_btnGirlInc_clicked(){
    girl->incAge();
};
void MainWindow::on_btnClear_clicked(){
    ui->txtEdit->clear();
};
